package com.yijdn.common.service;

import com.yijdn.common.utils.HttpContextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;

/**
 * @author zww
 * @date 2018-03-25 12:36
 * <p>
 * Email 971762302@qq.com
 * <p>
 * Describe:
 */
@Component("localeMessageSourceService")
public class LocaleMessageSourceService {

    @Autowired
    private MessageSource messageSource;

    /**
     * 获取指定code消息
     * @param code
     * @return
     */
    public String getMessage(String code) {

        return getMessage(code, null);

    }


    /**
     * @param code ：对应messages配置的key.
     * @param args : 数组参数.
     * @return
     */
    public String getMessage(String code, Object[] args) {

        return getMessage(code, args, "");

    }


    /**
     * @param code           ：对应messages配置的key.
     * @param args           : 数组参数.
     * @param defaultMessage : 没有设置key的时候的默认值.
     * @return
     */
    public String getMessage(String code, Object[] args, String defaultMessage) {
        /**
         * 从请求中获取locale ,zh_CN,en_US
         */
        HttpServletRequest request = HttpContextUtils.getRequest();
        Locale locale =RequestContextUtils.getLocale(request);

        return messageSource.getMessage(code, args, defaultMessage, locale);

    }
}
